package com.atguigu.tingshu.album.consumer;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Arrays;

/***
 * Redis消费者，专辑发生修改删除操作，都要把专辑从Redis中删除
 */
@Component
@Log4j2
public class RedisMessageConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @RabbitListener(queues = "album_Search_Queue_Redis")
    public void redisConsumer(Channel channel, Message message){
        //接受队列消息
        byte[] body = message.getBody();
        Long albumId = Long.valueOf(new String(message.getBody()));
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try{
            //删除Redis中的专辑
            redisTemplate.delete("getAlbumInfo:"+ Arrays.asList(albumId).toString());
            //删除Redis中的统计数据
            redisTemplate.delete("getAlbumInfoStat:" + Arrays.asList(albumId));
            //手动确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //判断是不是第一次发送
            if (messageProperties.getRedelivered()){
                //日志记录消息消费失败原因
                log.error("删除专辑失败，专辑ID："+albumId+"失败原因："+
                        e.getMessage());
                //是否将消息重新放回队列
                channel.basicReject(deliveryTag,false);
            }else {
                //是第一次发送，就将消息放回消息队列重新消费一次
                //延迟二删
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
